package com.sbs.gaoxinqutoilet.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.bin.david.form.core.SmartTable;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.base.BaseBackFragment;
import com.sbs.gaoxinqutoilet.entity.HomeMenuEntity;
import com.sbs.gaoxinqutoilet.entity.TongjiEntity;
import com.sbs.gaoxinqutoilet.eventbus.EventCenter;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.EventConstant;
import com.sbs.gaoxinqutoilet.utils.GsonTools;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by 聪明一只哈 on 2018/6/25.
 * Time: 2018/6/25  16:56
 */

public class ToiletStatisTicalFragment extends BaseBackFragment {

    //传过来的改造档案数据  存储在Bundle中
    private static final String STATISTICAL_FILE = "statistical_file";
    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_iv_menu)
    ImageView toolbarIvMenu;
    @BindView(R.id.toolbar_tv_menu)
    TextView toolbarTvMenu;
    @BindView(R.id.toolbar_rl_menu)
    AutoRelativeLayout toolbarRlMenu;
    @BindView(R.id.tongji_trefresh)
    SmartRefreshLayout tongjiTrefresh;
    @BindView(R.id.tongji_table)
    SmartTable<TongjiEntity.DataBean> tongjiTable;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    Unbinder unbinder;
    private HomeMenuEntity homemenu_buildfile;

    private int pageSize = 5;
    private int index;


    public static ToiletStatisTicalFragment newInstance(HomeMenuEntity homeMenuEntity) {
        Bundle args = new Bundle();
        args.putSerializable(STATISTICAL_FILE, homeMenuEntity);
        ToiletStatisTicalFragment fragment = new ToiletStatisTicalFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_statistical, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(inflater);
        initListener();

        return attachToSwipeBack(view);
    }


    private void initView(LayoutInflater inflater) {
        EventBus.getDefault().register(this);
        toolbarTitle.setText("改厕进度统计");
        //返回按钮
        toolbarBack.setVisibility(View.VISIBLE);
        //设置回键
        initToolbarBack(toolbar);



        //获取传递过来的值
        Bundle arguments = getArguments();
        if (arguments != null) {
            homemenu_buildfile = (HomeMenuEntity) arguments.getSerializable(STATISTICAL_FILE);
            if (homemenu_buildfile != null) {
                Log.i("统计页面", "initView: " + homemenu_buildfile.getFunc_name() + "~~~" + homemenu_buildfile.getFunc_id());
                //showShortToast(homemenu_buildfile.getFunc_name()+"~~~"+homemenu_buildfile.getFunc_id());
            }

        }

        //初始化index
        index = 0;

        //添加刷新头和尾
        SinaRefreshView sinaHeader = new SinaRefreshView(_mActivity);
        sinaHeader.setArrowResource(R.drawable.arrow);
        sinaHeader.setTextColor(0xff745D5C);



        tongjiTrefresh.setRefreshHeader(new ClassicsHeader(_mActivity));

        tongjiTrefresh.setRefreshFooter(new ClassicsFooter(_mActivity));



        //去掉顶部ABC
        tongjiTable.getConfig().setShowTableTitle(true);

    }


    private boolean isFrist = true;
    private void initListener() {

        tongjiTrefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                index=0;
               // showLoadingDialog();
                new Handler() {
                }.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadMoreData(index, pageSize,isFrist);
                    }
                }, 500);

                //refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        tongjiTrefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                index++;

                //showLoadingDialog();
                new Handler() {
                }.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadMoreData(index*pageSize, pageSize,true);
                    }
                }, 500);


            }
        });


    }


    /**
     * eventbus 页面跳转,事件接受
     *
     * @param center
     */
    @Subscribe
    public void onEventReceive(EventCenter center) {

        if (center.getEventCode() == EventConstant.UPLOAD_BUY_MODIFY) {
            //提交成功
            LogUtils.e("显示", "刷新");
            new Handler() {
            }.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // requestRefresh();
                }
            }, 500);
        }
    }

    /**
     * 页面加载动画结束就调用  loadMoreData(index, pageSize);
     * 所以  将两个方法紧挨着
     *
     * @param savedInstanceState
     */
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        //添加家在逻辑
        requestRefresh();


    }

    private void requestRefresh() {

        //设置出现刷新状态的头部
        if (tongjiTrefresh != null) {
            tongjiTrefresh.finishRefresh();
        }
        index = 0;

        loadMoreData(index, pageSize,isFrist);
    }



    private void loadMoreData(final int index, final int pageSize, final boolean isFoot) {

        final String tongji_Url = HttpApis.tongjiDate;


        HashMap<String, String> params = new HashMap<>();
        params.put("iud", homemenu_buildfile.getIud());
        params.put("start", String.valueOf(index));
        params.put("pagesize", String.valueOf(pageSize));

        HttpUtils.requestGet(_mActivity, tongji_Url,params, new Request(){
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);

                Log.i("buildfile_success", jsonStr);

                TongjiEntity tongjiEntity = GsonTools.changeGsonToBean(jsonStr, TongjiEntity.class);
                List<TongjiEntity.DataBean> data = tongjiEntity.getData();
                String recordsTotal = tongjiEntity.getRecordsTotal();
                try {
                    if(index==0) {
                        tongjiTrefresh.finishRefresh();
                        tongjiTable.setData(null);
                        tongjiTable.setData(data);

                    }else{

                        int size = tongjiTable.getTableData().getT().size();
                        size=size+pageSize;
                        int totalPageSize= Integer.parseInt(recordsTotal);
                        if(size<totalPageSize){
                            tongjiTable.addData(data,isFoot);
                        }
                        Log.i("hashiqisize", "lineSize: "+size);
                        tongjiTrefresh.finishLoadMore();

                    }
                    cancelLoadingDialog();
                }catch (Exception e){

                }
            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("buildfile_error", error);
                if(!isFoot) {
                    tongjiTrefresh.finishRefresh(false);
                }else{
                    tongjiTrefresh.finishLoadMore(false);
                }
                cancelLoadingDialog();
            }

        });

    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();
    }
}
